/**
 *
 */
package com.py.credit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.logs.DebugLogger;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.entity.CreditReport;
import com.py.credit.entity.Hcbg;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.BasicTableFieldEnum;
import com.py.credit.service.*;
import com.py.credit.service.impl.BgdzServiceImpl;
import com.py.credit.utils.*;
import com.py.credit.utils.elasticsearch.EsPage;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dd
 *
 */
@RestController
@RequestMapping(value = "/ssearch")
public class SsearchController {

    private final static String FRONT_TABLE_ID = "ssearch";

    @Autowired
    private SSearchService sSearchService;

    @Autowired
    private ShareLogService shareLogService;

    @Autowired
    private ScontentService sContentService;

    @Autowired
    private RemoteBaseService remoteBaseService;

    @Autowired
    private BgdzServiceImpl bgdzService;

    @Autowired
    private CreditReportService creditReportService;
    
    @Autowired
    private LhjcHongHeimdService lhjcHongHeimdService;

    @Value("${absolutepath}")
    private String absolutepath;

    @Value("${pdfJsPath}")
    private String pdfJsPath;

    @Value("${googlePath}")
    private String googlePath;

    @Value("${pdfPagePath}")
    private String pdfPagePath;

    @Value("${useEs}")
    private boolean useEs;

    @RequestMapping(value = "/getTableList.json")
    public RestServiceResult<List<Map<String, Object>>> getTableList(
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page) {

        List<String> showColumns = BasicTableFieldEnum.getDefaultShowColumnEN(kId);

        String[] additionalColumns = {"tybm"};

        List<Map<String, Object>> tableList = sSearchService.getByConditionForPage(kId, showColumns, additionalColumns,
                condition, page);

        return new RestServiceResult<>(page.getTotalCount(), tableList);

    }
    @IgnoreAuthority
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getDetail.json")
    public RestServiceResult<Object> getDetail(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId,
            @RequestParam(value = "keyWord", defaultValue = "", required = true) String keyWord,
            HttpServletRequest request) {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        String username = "";
        String realName = "";
        long id = 0L;
        long deptId = 0;
        SysUser userInfo = null;
      

            userInfo = user.getData();

            if (userInfo.getId()!=null) {

                username = userInfo.getUsername();

                realName = userInfo.getRealName();

                deptId = userInfo.getOfficeId();

                id = userInfo.getId();
          } else {
        	userInfo.setId(1l);
        	userInfo.setRealName("系统管理员");
        	userInfo.setOfficeId(51);
        	 Map<String, Object> detail = sContentService.getDetail(kId, tybm, "YZS", userInfo);

             sSearchService.addHistory(tybm, kId, id);

             shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), username,
                     realName, deptId, keyWord);
             // 根据样式展示
             List<TableResult> data = sSearchService.assembleTableComponentForYZS((List<TableResult>) detail.get("results"));

             return new RestServiceResult<Object>(data);
        }

        Map<String, Object> detail = sContentService.getDetail(kId, tybm, "YZS", userInfo);

        sSearchService.addHistory(tybm, kId, id);

        shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), username,
                realName, deptId, keyWord);
        // 根据样式展示
        List<TableResult> data = sSearchService.assembleTableComponentForYZS((List<TableResult>) detail.get("results"));

        return new RestServiceResult<Object>(data);

    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/selectInfo.json")
    public RestServiceResult<List<Map<String, Object>>> creditInfoSelect(
    		 @RequestParam(value = "condition", defaultValue = "")String condition,
            HttpServletRequest request) {
    	Map<String,Object> map = JSON.parseObject(condition);
    	Page page  = new Page();
    	String param = null;				
		String type = null;
		String range = null;
		String cxlb = null;
		String path = null;
    	if(map.size()>0) {
			if(map.get("param") != null) {
				param =	String.valueOf(map.get("param"));
			}
			if(map.get("type") != null) {
				type =	String.valueOf(map.get("type"));
			}
			if(map.get("range") != null) {
				range =	String.valueOf(map.get("range"));
			}
			if(map.get("cxlb") != null) {
				cxlb =	String.valueOf(map.get("cxlb"));
			}
			
		}
    	page.setLimit(Integer.parseInt(String.valueOf(map.get("limit"))));		
		page.setPage(Integer.parseInt(String.valueOf(map.get("page"))) /Integer.parseInt(String.valueOf(map.get("limit"))) + 1);
    	List<Map<String, Object>> detail = new ArrayList<Map<String, Object>>();
    	 String tablename = "";
    	 String cloum = "";
    	 if("企业".equals(cxlb)) {
    		 tablename=  "t_zoo_subject_unique_100000";
    		 if("like".equals(type)) {
    			 if(map.get("path").equals("index")) {
    				 detail =  sContentService.getcreditInfoLikeForPage(param, tablename,range,page);
    			 }else {
    	    		detail =  sContentService.getcreditInfoSelectByLikeForPage(param, tablename,range,page);
    			 }
    			 }else {
    	    		detail =  sContentService.getcreditInfoSelectByAccurateForPage(param, tablename,range,page);
    	    	}
    	       
    	 }else {
    		 tablename=  "t_zoo_subject_unique_100002";
    		 if("like".equals(type)) {
    	    		detail =  sContentService.getFQYFRcreditInfoSelectByLikeForPage(param, tablename,range,page);
    	    	}else {
    	    		detail =  sContentService.getFQYFRcreditInfoSelectByAccurateForPage(param, tablename,range,page);
    	    	}
    	 }
    	
    	
       
    	Integer pageCount= detail.size();

        return new RestServiceResult<>(pageCount, detail);

    }
    @IgnoreAuthority
    @RequestMapping(value = "/selectInfoDetail.json")
    public RestServiceResult<Object> selectInfoDetail(
    		  @RequestParam(value = "condition", defaultValue = "", required = true)String condition,
            HttpServletRequest request) {
    	Map<String,Object> map = JSON.parseObject(condition);
    	String kid = null;
		String tybm = null;
		String qymc = null;
    	if(map.size()>0) {
			if(map.get("kid") != null) {
				kid =	String.valueOf(map.get("kid"));
			}
			if(map.get("tybm") != null) {
				tybm =	String.valueOf(map.get("tybm"));
			}
			if(map.get("qymc") != null) {
				qymc =	String.valueOf(map.get("qymc"));
			}
		}
    	List<String> game = new ArrayList<String>();
    	if(kid.equals("100000")) {
    		Map<String, Object> detail = sContentService.getDetail(kid, tybm, "JKSQ", null);
//    		System.out.println(JSONObject.toJSON(detail));
            sSearchService.addHistory(tybm, kid, -1);

            shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), null,
            		null, -1, null);
            // 根据样式展示
            Map<String,Object> data = sSearchService.assembleTableComponentForMHWZ((List<TableResult>) detail.get("results"),tybm);	
//            System.out.println(JSONObject.toJSON(data));
            //信用信息详情查询日志
            Map<String,Integer> count =  sSearchService.selectInfoDetailLog(qymc,tybm);
            if(count!=null&&!count.isEmpty()) {
        	   
        	   //修改信息详情查询次数
               sSearchService.updateInfoDetailLog(qymc,tybm);
               data.put("selectcount", count.get("count")+1);
           }else {
        	   //新增信息详情查询次数
               sSearchService.addInfoDetailLog(qymc,tybm);
               data.put("selectcount", 1);
           }
           Page page = new Page();
           page.setLimit(1);
           page.setPage(1);
           Integer J = 0;
           Integer C = 0;
           List<LinkedHashMap> selectHongheiMdForPage = lhjcHongHeimdService.selectHongheiMdForPage("J","C", tybm, "", "", game, page);
           List<LinkedHashMap> selectHongheiMdForPage2 = lhjcHongHeimdService.selectHongheiMdForPage("C","C", tybm, "", "", game, page);
           if(selectHongheiMdForPage !=null && selectHongheiMdForPage.size()>0) {
        	   J=1;
           }
           if(selectHongheiMdForPage2 !=null && selectHongheiMdForPage2.size()>0) {
        	   C=1;
           }
           data.put("jl", J);
           data.put("cj", C);
            return new RestServiceResult<Object>(data);

    	}else {
    		TableResult jbxx = new TableResult();
    		jbxx.setTableNameCN("非企业法人登记信息");
    		jbxx.setTableNameEN("1000020010028_DEfBZD5dof");
    		jbxx.setCategoryName("基本信息");
    		TableResult frxzxk = new TableResult();
    		frxzxk.setTableNameCN("法人行政许可");
    		frxzxk.setTableNameEN("1000000010001_3ioj4GeZQU");
    		frxzxk.setCategoryName("行政许可");
    		TableResult frxzcf = new TableResult();
    		frxzcf.setTableNameCN("法人行政处罚");
    		frxzcf.setTableNameEN("1000000010002_XSni4zSzP0");
    		frxzcf.setCategoryName("行政处罚");
    		List<TableResult> list = new ArrayList<>();
    		list.add(jbxx);
    		list.add(frxzxk);
    		list.add(frxzcf);
    		 // 根据样式展示
            Map<String,Object> data = sSearchService.assembleTableComponentForMHWZ(list,tybm);	
            //信用信息详情查询日志
            Map<String,Integer> count =  sSearchService.selectInfoDetailLog(qymc,tybm);
            if(count!=null&&!count.isEmpty()) {
         	   
         	   //修改信息详情查询次数
                sSearchService.updateInfoDetailLog(qymc,tybm);
                data.put("selectcount", count.get("count")+1);
            }else {
         	   //新增信息详情查询次数
                sSearchService.addInfoDetailLog(qymc,tybm);
                data.put("selectcount",1);
            }
            Page page = new Page();
            page.setLimit(1);
            page.setPage(1);
            Integer J = 0;
            Integer C = 0;
            List<LinkedHashMap> selectHongheiMdForPage = lhjcHongHeimdService.selectHongheiMdForPage("J","P", qymc, "", "", game, page);
            List<LinkedHashMap> selectHongheiMdForPage2 = lhjcHongHeimdService.selectHongheiMdForPage("C","P", qymc, "", "", game, page);
            if(selectHongheiMdForPage !=null && selectHongheiMdForPage.size()>0) {
         	   J=1;
            }
            if(selectHongheiMdForPage2 !=null && selectHongheiMdForPage2.size()>0) {
         	   C=1;
            }
            data.put("jl", J);
            data.put("cj", C);
            return new RestServiceResult<Object>(data);
           
    	}
        

       
    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/xyhcselectInfoDetail.json")
    public RestServiceResult<Object> xyhcselectInfoDetail(
    		  @RequestParam(value = "qymc", defaultValue = "", required = true)String qymc,
    		  @RequestParam(value = "tybm", defaultValue = "", required = true)String tybm,
    		
            HttpServletRequest request) {   
    	List<String> game = new ArrayList<String>();   	
    		Map<String, Object> detail = sContentService.getDetail("100000", tybm, "JKSQ", null);
            sSearchService.addHistory(tybm, "100000", -1);
            shareLogService.add(1, (String) detail.get("category"), HttpServletHelper.getGuestIP(request), null,
            		null, -1, null);
            // 根据样式展示
            Map<String,Object> data = sSearchService.xyhcassembleTableComponentForMHWZ((List<TableResult>) detail.get("results"),qymc,tybm);	
                  
           Page page = new Page();
           page.setLimit(1);
           page.setPage(1);
           Integer J = 0;
           Integer C = 0;
           List<LinkedHashMap> selectHongheiMdForPage = lhjcHongHeimdService.selectHongheiMdForPage("J","C", qymc, "", "", game, page);
           List<LinkedHashMap> selectHongheiMdForPage2 = lhjcHongHeimdService.selectHongheiMdForPage("C","C", qymc, "", "", game, page);
           if(selectHongheiMdForPage !=null && selectHongheiMdForPage.size()>0) {
        	   J=1;
           }
           if(selectHongheiMdForPage2 !=null && selectHongheiMdForPage2.size()>0) {
        	   C=1;
           }
           data.put("jl", J);
           data.put("cj", C);
            return new RestServiceResult<Object>(data);
    	}
        

       
  
    /* 郑州核查报告定制数据接口 */
    @RequestMapping(value = "/getDetailData.json")
    public RestServiceResult<Object> getDetailData(
            @RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
            @RequestParam(value = "kId", defaultValue = "", required = true) String kId) {
        Map<String, Object> result = new HashMap<String, Object>();

        Map<String, Object> detail = sContentService.getDetail(kId, tybm, "XYHC", null);

        String number = creditReportService.getReportSerials(kId, DateUtils.getCurrentTime());

        Hcbg latest = bgdzService.getLatest();

        latest.setReportNo(latest.getReportNo() + DateUtils.getStringOfTodayDate(DateUtils.SIMPLE_PATTERN) + number);

        result.put("tableData", detail.get("results"));

        result.put("elementData", latest);

        return new RestServiceResult<Object>(result);

    }

    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
                                                    @RequestParam(value = "kId", defaultValue = "", required = true) String kId, HttpServletRequest request) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                MapCache.set(userInfo.getId() + "_" + kId + "_" + FRONT_TABLE_ID, columns);

            } else {

                ExceptionLogger.error("SsearchController#addShowColunms", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#addShowColunms", "未获取到当前用户信息！");
        }

        return new RestServiceResult<String>();
    }

    @RequestMapping(value = "/getOptionalColums/{kId}.json")
    public RestServiceResult<List<OptionalColumn>> getOptionalColums(@PathVariable(value = "kId") String kId) {

        return new RestServiceResult<List<OptionalColumn>>(BasicTableFieldEnum.getOptionalColumns(kId));

    }

    @RequestMapping(value = "/getAdvancedConditionColumns/{kId}.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns(
            @PathVariable(value = "kId") String kId) {

        return new RestServiceResult<List<OptionalColumn>>(BasicTableFieldEnum.getAdvancedConditionColumns(kId));

    }

    @RequestMapping(value = "/export.json")
    public void export(@RequestParam(value = "kId") String kId,
                       @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
                       @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
                       HttpServletResponse response) throws IOException {

        page.setLimit(1000);

        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);

        List<OptionalColumn> optionalColumns = BasicTableFieldEnum.getOptionalColumns(kId);

        List<Map<String, Object>> tableList = sSearchService.getByConditionForPage(kId, showColumns, null, condition,
                page);

        ExcelUtil.downloadExcel(response, tableList, "共享查询列表", "共享查询列表", showColumns, optionalColumns);

    }
    @IgnoreAuthority
    @RequestMapping(value = "/getKeyWord.json")
    public RestServiceResult<List<Map<String, String>>> getKeyWord(@RequestParam(value = "kId") String kId,
                                                                   @RequestParam(value = "name") String input) {

        List<Map<String, String>> keyWords = null;

        if (StringUtils.isNotBlank(input)) {
            if (useEs) {
                keyWords = sSearchService.getKeyWordsByEs(kId, input, new EsPage());
            } else {
                keyWords = sSearchService.getKeyWords(kId, input);
            }
        }
        return new RestServiceResult<List<Map<String, String>>>(
                keyWords == null ? new ArrayList<Map<String, String>>() : keyWords);

    }

    @IgnoreAuthority
    @RequestMapping(value = "/getSubjectList.json")
    public RestServiceResult<List<Map<String, String>>> getSubjectLsit(@RequestParam(value = "kId") String kId,
                                                                       @RequestParam(value = "input") String input, Page page, EsPage esPage) {

        List<Map<String, String>> keyWords = null;

        int total = 0;

        if (StringUtils.isNotBlank(input)) {

            if (useEs) {

                keyWords = sSearchService.getKeyWordsByEs(kId, input, esPage);

                total = esPage.getTotalCount();

            } else {

                keyWords = sSearchService.getSubjectLsitForPage(kId, input, page);

                total = page.getTotalCount();
            }

        }
        return new RestServiceResult<List<Map<String, String>>>(total,
                keyWords == null ? new ArrayList<Map<String, String>>() : keyWords);

    }

    @RequestMapping(value = "/getCollectionStatistics.json")
    public RestServiceResult<Map<String, Object>> getCollectionStatistics() {

        Map<String, Object> collectionStatistics = sSearchService.getCollectionStatistics();

        return new RestServiceResult<Map<String, Object>>(collectionStatistics);

    }
    @IgnoreAuthority
    @RequestMapping(value = "/getResourceStatistics.json")
    public RestServiceResult<Map<String, Integer>> getResoucrStatistics(@RequestParam(value = "tybm") String tybm) {

        Map<String, Integer> map = sSearchService.getResourceStatistics(tybm);

        return new RestServiceResult<Map<String, Integer>>(map);

    }

    @RequestMapping(value = "/getHistoryList.json")
    public RestServiceResult<List<Map<String, Object>>> getHistoryList(HttpServletRequest request,
                                                                       @RequestParam(value = "kId") String kId) {

        long userId = 0L;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userId = userInfo.getId();

            } else {

                ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
        }

        List<Map<String, Object>> historyLsit = sSearchService.getSharingSearchHistoryList(userId, kId);

        List<Map<String, Object>> uniqueList = new ArrayList<Map<String, Object>>(historyLsit.size());

        for (Map<String, Object> map : historyLsit) {

            Map<String, Object> singleReocrd = sSearchService.getUniqueList(map);

            if ("100001".equals(kId) && !CollectionUtils.isEmpty(singleReocrd)) {

                String idEncrypt = NumberUtils.idEncrypt((String) singleReocrd.get("B000002"));
                singleReocrd.put("B000002", idEncrypt);

            }

            if (singleReocrd != null) {

                uniqueList.add(singleReocrd);

            }

        }

        return new RestServiceResult<List<Map<String, Object>>>(uniqueList);

    }

    @Deprecated
    @RequestMapping(value = "/getReport2.json")
    public RestServiceResult<String> getReport(@RequestParam(value = "keyword") String tybm,
                                               @RequestParam(value = "qymc") String qymc, @RequestParam(value = "shtydm") String shtydm,
                                               HttpServletRequest request) throws Exception {
        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String username = "";
        String officeName = "";
        String realName = "";
        long deptId = 0;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                username = userInfo.getUsername();
                officeName = userInfo.getOfficeName();
                realName = userInfo.getRealName();
                deptId = userInfo.getOfficeId();
            } else {
                ExceptionLogger.error("SsearchController#reportPreview", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("SsearchController#reportPreview", "未获取到当前用户信息！");
        }
        shareLogService.add(2, "信用核查", HttpServletHelper.getGuestIP(request), username, realName, deptId, qymc);
        creditReportService.createCreditReport(absolutepath, tybm, qymc); // 将目录信息入库
        CreditReport report = new CreditReport();
        report.setLocation(ResourcePath.CREDIT_REPORT_DIR + tybm + "/" + ResourcePath.CREDIT_REPORT_NAME);
        report.setEntityTybm(tybm);
        report.setEntityName(qymc);
        report.setEntityTyshxydm(shtydm);
        report.setGenerator(username);
        report.setType(1);
        report.setGeneratorDept(officeName);
        creditReportService.add(report);
        return new RestServiceResult<>();

    }

    @RequestMapping(value = "/getReportData.json")
    public RestServiceResult<Map<String, Object>> getReportData(@RequestParam(value = "tybm") String tybm,
                                                                @RequestParam(value = "kId") String kId) {

        Map<String, Object> reportData = creditReportService.getReportData(tybm, kId);

        return new RestServiceResult<Map<String, Object>>(reportData);

    }

    @RequestMapping(value = "/getReport.json")
    public RestServiceResult<String> generateReport(@RequestParam(value = "kId") String kId,
                                                    @RequestParam(value = "tybm") String tybm,
                                                    @RequestParam(value = "keyword", defaultValue = "", required = true) String keyword,
                                                    @RequestParam(value = "subword", defaultValue = "", required = true) String subword,
                                                    HttpServletRequest request, HttpServletResponse response) {

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        String username = "";
        String officeName = "";
        String realName = "";
        long deptId = 0;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                username = userInfo.getUsername();

                officeName = userInfo.getOfficeName();
                realName = userInfo.getRealName();

                deptId = userInfo.getOfficeId();
            } else {

                ExceptionLogger.error("SsearchController#reportPreview", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#reportPreview", "未获取到当前用户信息！");
        }
        String filePath = absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm;
        Map<String, Object> templateData = this.getTemplateData(tybm, kId);
        templateData.put("firstTitle", keyword);
        boolean googleConvent = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_template_freemarker.html", filePath, keyword+".pdf", absolutepath);

        /*boolean data = HtmlToPdfUtils.googleConvent(pdfJsPath,
                pdfPagePath + "/tybm=" + tybm + "/kId=" + kId + "/keyword=" + keyword,
                absolutepath + ResourcePath.CREDIT_REPORT_DIR + tybm, ResourcePath.CREDIT_REPORT_NAME, null, true,
                googlePath);*/

        if (googleConvent) {
            shareLogService.add(2, "信用核查", HttpServletHelper.getGuestIP(request), username, realName, deptId, keyword);
            // 将目录信息入库
            CreditReport report = new CreditReport();
            report.setLocation(ResourcePath.CREDIT_REPORT_DIR + tybm + "/" + keyword+".pdf");
            report.setEntityTybm(tybm);
            report.setEntityName(keyword);
            report.setEntityTyshxydm(subword);
            report.setGenerator(username);
            report.setEntityKId(kId);
            report.setType(1);
            report.setGeneratorDept(officeName);
            creditReportService.add(report);

        } else {

            throw new ServiceException("生成报告失败");

        }

        return new RestServiceResult<String>();
    }
    
    /**
     * 一站式查询风险分析
     */
    @IgnoreAuthority
    @RequestMapping(value = "/riskdetail.json")
    public RestServiceResult<Map<String, Object>> riskdetail(@RequestParam(value = "tybm") String tybm,
                                                                @RequestParam(value = "kId") String kId,
                                                                @RequestParam(value = "keyWord", defaultValue = "", required = true) String keyWord,
                                                                HttpServletRequest request) {
    	RestServiceResult<Map<String, Object>> result =	new RestServiceResult<Map<String, Object>>();
    	  RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

    	try {
    		
    		Map<String, Object> riskdata = sContentService.getriskdata(tybm,keyWord);
    		 return new RestServiceResult<Map<String, Object>>(riskdata);
		} catch (Exception e) {
			ExceptionLogger.error("SsearchController#riskdetail", "风险分析获取信息异常！" + e.getMessage(),
					e);
			result.setMsg("风险分析获取信息失败");
			return result;
		}
    }

    /**
     * 获取生成PDF需要的数据
     * @param tybm
     * @param kId
     * @return
     */
    private Map<String, Object> getTemplateData(String tybm, String kId) {
        Map<String, Object> result = new HashMap<String, Object>();

        String number = creditReportService.getReportSerials(kId, DateUtils.getCurrentTime());
        Map<String, Object> detail = sContentService.getDetail(kId, tybm, "XYHC", null);
        Map<String, List<TableResult>> map = new HashMap<String, List<TableResult>>();
        List<TableResult> assembleTableComponent = sSearchService.assembleTableComponent((List<TableResult>) detail.get("results"));

        StringBuilder catalogList = new StringBuilder();
        StringBuilder tableList = new StringBuilder();
        for (TableResult tableResult : assembleTableComponent) {
            String categoryCode = tableResult.getCategoryCode();
            if (map.containsKey(categoryCode)) {
                List<TableResult> list = map.get(categoryCode);
                list.add(tableResult);
            } else {
                List<TableResult> rs = new ArrayList<TableResult>();
                rs.add(tableResult);
                map.put(categoryCode, rs);
            }
        }

        int index = 0;
        for(String key : map.keySet()) {
            index ++;
            List<TableResult> trList = map.get(key);
            for(int i =0; i<trList.size(); i++) {
                TableResult tableResult = trList.get(i);
                if (i == 0) {
                    catalogList.append("<div>").append(index).append(tableResult.getCategoryName()).append("</div><p>");
                    tableList.append("<h3><span>").append(tableResult.getCategoryName()).append("</span></h3>");
                }
                tableList.append("<div class=\"tableL\"><h4>").append(tableResult.getTableNameCN()).append("</h4>").append(tableResult.getTableComponent()).append("</div>");
                if (i == trList.size()-1) {
                    catalogList.append("<span>").append(tableResult.getTableNameCN()).append("</span>");
                } else {

                    catalogList.append("<span>").append(tableResult.getTableNameCN()).append("、</span>");
                }
            }
            catalogList.append("</p>");

        }

        Hcbg latest = bgdzService.getLatest();
        latest.setReportNo(latest.getReportNo() + DateUtils.getStringOfTodayDate(DateUtils.SIMPLE_PATTERN) + number);
        result.put("firstReportNum", latest.getReportNo());
        result.put("reportProducer", latest.getReportProducer());
        result.put("reportDate", DateUtils.getStringOfTodayDate("yyyy年MM月dd日"));
        result.put("reportStatment", latest.getReportStatment());

        result.put("catalogList", catalogList.toString());
        result.put("tableList", tableList.toString());
        if (StringUtils.isNotBlank(latest.getWatermarker())) {
            result.put("waterPath", latest.getWatermarker().substring(0, latest.getWatermarker().lastIndexOf("/") + 1));
            result.put("water", latest.getWatermarker().substring(latest.getWatermarker().lastIndexOf("/") + 1));
        }
        return result;
    }

}
